package favorite

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckShopGoodsFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCheckShopGoodsFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckShopGoodsFavoriteLogic {
	return &CheckShopGoodsFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckShopGoodsFavoriteLogic) CheckShopGoodsFavorite(
	req *types.CheckShopGoodsFavoriteReq,
	headers *[]*types.Header,
) (resp *types.CheckShopGoodsFavoriteResp, err error) {
	if req.ProductId == nil || *req.ProductId == 0 {
		return nil, resultx.NewErrCode(resultx.PRODUCT_ID_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	preload := "forumUserCollect:Id"
	// 构造查询条件
	var filters []string
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	filters = append(filters, "PlatformId,equalTo:"+strconv.FormatInt(int64(globalkey.ThirdPartyPlatformWechatMini), 10))
	filters = append(filters, "ObjectId,equalTo:"+strconv.FormatInt(int64(*req.ProductId), 10))
	filters = append(filters, "ObjectType,equalTo:"+strconv.FormatInt(int64(globalkey.AttachmentLogTypeProduct), 10))
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))

	res, err := l.svcCtx.ForumRpc.GetUserCollectList(l.ctx, &forumclient.BaseListReq{
		Limit:      uint32(1),
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	resp = &types.CheckShopGoodsFavoriteResp{}
	if len(res.List) > 0 {
		resp.Favorited = pointy.GetPointer(true)
	}

	return resp, nil
}
